
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.Employee;
import com.cmc.dao.EmployeeDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class EmployeeDaoHibernate extends BaseDaoHibernate implements EmployeeDao {

    /**
     * @see com.cmc.dao.EmployeeDao#getEmployees(com.cmc.model.Employee)
     */
    public List getEmployees(final Employee employee) {
        //return getHibernateTemplate().find("from Employee");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (employee == null) {
            return getHibernateTemplate().find("from Employee");
        } else {
            // filter on properties set in the employee
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(employee).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Employee.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.EmployeeDao#getEmployee(Long id)
     */
    public Employee getEmployee(final Long id) {
        Employee employee = (Employee) getHibernateTemplate().get(Employee.class, id);
        if (employee == null) {
            log.warn("uh oh, employee with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Employee.class, id);
        }

        return employee;
    }

    /**
     * @see com.cmc.dao.EmployeeDao#saveEmployee(Employee employee)
     */    
    public void saveEmployee(final Employee employee) {
        getHibernateTemplate().saveOrUpdate(employee);
    }

    /**
     * @see com.cmc.dao.EmployeeDao#removeEmployee(Long id)
     */
    public void removeEmployee(final Long id) {
        getHibernateTemplate().delete(getEmployee(id));
    }
}
